// wait_group 实现有条件的等待
#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>
#include <iostream>
#include <signal.h>
using std::cout;
using std::cerr;
static WFFacilities::WaitGroup waitGroup(1);
void handler(int signum){
    cout << "done\n";
    waitGroup.done();
}
void httpCallback(WFHttpTask *httpTask){ // 框架会在百度回复响应以后，调用httpCallback函数
    cout << "callback is called!\n";
    protocol::HttpRequest *req = httpTask->get_req(); // 获取请求
	protocol::HttpResponse *resp = httpTask->get_resp(); // 获取响应

	int state = httpTask->get_state(); // 获取状态
	int error = httpTask->get_error(); // 获取错误原因
	switch (state){
	case WFT_STATE_SYS_ERROR:
		cerr <<"system error: " << strerror(error) << "\n";
		break;
	case WFT_STATE_DNS_ERROR:
		cerr <<"DNS error: "  << gai_strerror(error) << "\n";
		break;
	case WFT_STATE_SSL_ERROR:
		cerr <<"SSL error\n";
		break;
	case WFT_STATE_TASK_ERROR:
		cerr <<"Task error\n";
		break;
	case WFT_STATE_SUCCESS:
		break;
	}
	if (state != WFT_STATE_SUCCESS){
		cerr <<"Failed. Press Ctrl-C to exit.\n";
		return;
	}

	// 把请求报文的起始行展示出来
	cerr << "method = " << req->get_method()
         << "version = " << req->get_http_version()
		 << "path&query = " << req->get_request_uri() << "\n";

    // 遍历请求报文的首部字段
    std::string name;
	std::string value;
	protocol::HttpHeaderCursor req_cursor(req); // cursor可以理解为一个迭代器
	while (req_cursor.next(name, value)){ // next负责取出下一个首部字段
		cerr << "name = " << name << " value = " << value << "\n";
    }
	
	// 响应的起始行
	cerr <<"version = " <<  resp->get_http_version()
         << "status code = " << resp->get_status_code()
         << "reason phrase = "  << resp->get_reason_phrase() << "\n";

    // 响应的首部字段
	protocol::HttpHeaderCursor resp_cursor(resp);
	while (resp_cursor.next(name, value)){
		cerr << "name = " << name << " value = " << value << "\n";
    }

	
	const void *body;
	size_t body_len;
	resp->get_parsed_body(&body, &body_len); // get_parsed_body找到响应报文的报文体
    cerr << static_cast<const char *>(body) << "\n";

}
int main(){
    signal(SIGINT,handler); // 注册信号
    // 用户调用工厂函数去创建一个任务
    WFHttpTask * httpTask =  WFTaskFactory::create_http_task(
        "http://www.baidu.com",
        //"http://localhost/en/index.html",
        10,
        10,
        httpCallback
    );
	// 找到请求
	protocol::HttpRequest *req = httpTask->get_req();
	req->set_method("POST");
	req->set_request_uri("/s?wd=123");
	req->add_header_pair("MyName","Workflow");
    // 用户把任务交给框架
    httpTask->start();
    // 用户就等待
    waitGroup.wait();
    cout << "finish!\n";
}
